//
//  AppDelegate.m
//  NewChat
//
//  Created by 马欢 on 16/2/27.
//  Copyright © 2016年 蓝鸥. All rights reserved.
//

#import "AppDelegate.h"
#import "RootViewController.h"
#import "UMSocial.h"
#import "UMSocialQQHandler.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialAlipayShareHandler.h"
#import <UMSocialSinaSSOHandler.h>
#import "LoginViewController.h"
#import "FindModel.h"
#import "ReplyModel.h"
#import "MHDataHelper.h"


//#import "UserModel.h"
#import "SKXCallViewController.h"
//#import <AVOSCloud/AVOSCloud.h>
#import <EaseMob.h>


@interface AppDelegate ()<EMChatManagerDelegate,EMCallManagerDelegate>

@property (nonatomic , strong) MBProgressHUD *loadingView;

@property (nonatomic , strong) UIViewController *loadingVC;

@property (nonatomic , strong) NSTimer *timer;

@property (nonatomic , strong) RootViewController * rootVC;

@property (nonatomic , strong) LoginViewController *presentVC;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc]init];
    self.rootVC = [[RootViewController alloc]init];
//    UINavigationController *rootNC = [[UINavigationController alloc]initWithRootViewController:rootVC];
    self.window.rootViewController = _rootVC;
    [FindModel registerSubclass];
    [ReplyModel registerSubclass];
//    [UserModel registerSubclass];
    self.window.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];

    [self.window makeKeyAndVisible];
#pragma mark============第三方分享========================
    //设置友盟授权
    [UMSocialData setAppKey:@"56dd84bfe0f55a58e80014bc"];
    
    
    //设置微信分享
    [UMSocialWechatHandler setWXAppId:@"wxd930ea5d5a258f4f" appSecret:@"db426a9829e4b49a0dcac7b4162da6b6" url:@"http://www.umeng.com/social"];
    
    //设置QQ分享
    [UMSocialQQHandler setQQWithAppId:@"1105161853" appKey:@"Pw9ZRpc01plOV0Oo" url:@"http://www.umeng.com/social"];
    
    //设置新浪的SSOK开关和回调地址
//    [UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:@"3373181826" RedirectURL:@"http://www.umeng.com/social"];
    
    NSLog(@"%ld",[MHDataHelper shareDataHelper].pushIndex);//一开始就让单例运行
#pragma mark=============================================
    
    
    
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];
    _presentVC = [storyBoard instantiateInitialViewController];
//    [self.window.rootViewController presentViewController:presentVC animated:NO completion:^{
//    
//    }];
    //集成leancloud存储服务
    
    [AVOSCloud setApplicationId:@"RVxNwkCViwKyKfYO17wbXuUb-gzGzoHsz"
                      clientKey:@"hSwm9mbx4NP9QAUHd33QHkCE"];


    //集成环信
    
    [[EaseMob sharedInstance] registerSDKWithAppKey:@"yanfa9#demo" apnsCertName:nil otherConfig:@{kSDKConfigEnableConsoleLogger:@(NO)}];
    
    [[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    
    
    //添加代理
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    
    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
    
    
    //检测自动登录
    
    if([[EaseMob sharedInstance].chatManager isAutoLoginEnabled]){
    
        NSLog(@"准备自动登录");
        
        self.window.rootViewController = self.rootVC;
        
        _loadingView = [MBProgressHUD showHUDAddedTo:self.window animated:YES];
        
        _loadingView.mode = MBProgressHUDModeIndeterminate;
        
        _loadingView.labelText = @"正在登陆";
                
        
    }else{


    
        self.window.rootViewController = _presentVC;
    

    }

    
    return YES;
}



//实现自动登录的回调
-(void)didAutoLoginWithInfo:(NSDictionary *)loginInfo error:(EMError *)error{
    
    if (!error) {
        
        NSLog(@"自动登录成功");
        
        NSError * err = nil;
        
        [AVUser logInWithUsername:loginInfo[@"username"] password:loginInfo[@"password"] error:&err];

        if (!err) {
            
            AVUser *user = [AVUser currentUser];
            [user setObject:@"在线" forKey:@"status"];
            [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    NSLog(@"在线状态保存成功");
                }
            }];
        
            [_loadingView hide:YES];
            
        }else{
            
            
            
            [_loadingView hide:YES];
            
            UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
                
            }];
            
            UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"自动登录失败" preferredStyle:(UIAlertControllerStyleAlert)];
            
            [con addAction:act];
            [self.window.rootViewController presentViewController:con animated:YES completion:nil];

            
        }

        
    }else{
        
        [_loadingView hide:YES];
        
        [AVUser logOut];
        
        
        
        UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            
            
            
        }];
        
        UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"自动登录失败" preferredStyle:(UIAlertControllerStyleAlert)];
        
        [con addAction:act];
        [self.window.rootViewController presentViewController:con animated:YES completion:nil];
        
        
        
        NSLog(@"自动登录失败");
    }
    
    
}

//从其他设备登录
-(void)didLoginFromOtherDevice{
    
    [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
        if (!error && info) {
            [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:NO];
            
            
            UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
                self.window.rootViewController = _presentVC;
                
            }];
            
            UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"账号在其他设备登录" preferredStyle:(UIAlertControllerStyleAlert)];
            
            [con addAction:act];
            [self.window.rootViewController presentViewController:con animated:YES completion:nil];

            
            
            NSLog(@"在其他设备登录");
        }
    } onQueue:nil];
    
}

#pragma mark========友盟 使用第三方登陆调用的2个方法==========


-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    
    
    BOOL result = [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil];
    
    //如果打开错误调用的接口
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
        
        
    }
    return result;
    
    
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     [UMSocialSnsService applicationDidBecomeActive];
    
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


//添加定时器
-(void)addTimer{
    
    
    self.timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(againAutoLogin) userInfo:nil repeats:YES];
    
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}
//取消定时器
-(void)cancelTimer{
    
    [self.timer invalidate];
    self.timer = nil;
    
}

-(void)againAutoLogin{
    
}

//暂时待定通话监控
-(void)callSessionStatusChanged:(EMCallSession *)callSession changeReason:(EMCallStatusChangedReason)reason error:(EMError *)error{
    
    
    if (callSession.status == eCallSessionStatusRinging) {
        
        SKXCallViewController *call = [[SKXCallViewController alloc] init];
        
        call.currentCall = callSession;
        
        call.chater = callSession.sessionChatter;
        
        [self.window.rootViewController presentViewController:call animated:YES completion:^{
            
        }];
    }
    
    
}


@end
